<?php
    define('IN_ADAGPS', TRUE); 

    // Include file config va file chua cac function can thiet
    include_once('cfg.php');
    include_once(CORE_PATH.'includes/functions.php'); 
    include_once(CORE_PATH.'includes/functions_index.php'); 
   
    // Set lang of app
    SetLang();    
    // Get menu ID
    
    // Phuog Search
    global $objTemplate, $objDbSelect,$lang;
    $lang = $_SESSION["lang"];   
    // Phuog Search
 /////////    
  // GetViewForCombo("blkcboView");// lấy danh sách view cho combo     
   
///////////
    $sModule =  'help_form';
                
    if(!isset($_SESSION['username'])){
        MsgBox1('Vui lòng đăng nhập để xem chức năng này!');
        Redirect('index.php');
    }
   // $tplUrl = "index.php?mid=$sMenuId&m=$sModule";  
                        
    // If template file is not exist, redirect to default        
    $tmplContent = TEMPL_PATH.$arrConfig['lang'].'/main_'.$sModule.'.html';
    
    $sIncFile = MODULE_PATH.'main_'.$sModule.'.php';
    $objXajax->registerFunction("updatevisible"); 
    $objXajax->registerFunction("saveIntroduce");
    $objXajax->registerFunction("fillIntroduce");
    $objXajax->registerFunction("fillorder");
    $objXajax->registerFunction("fillArange"); 
    $objXajax->registerFunction("saveArange"); 
    $objXajax->registerFunction("ajxHelp");
    $objXajax->registerFunction("renamehelp");
    $objXajax->registerFunction("deletehelp");
    $objXajax->registerFunction("copyhelp");
    $objXajax->registerFunction("Searchnew"); 
    $objXajax->registerFunction('ajxFillData');      // Phuog Search ham chuan bi sua
    $objXajax->registerFunction('ajxSaveEdit');      // Phuong Search thuc thi sua/them
    $objXajax->registerFunction("GetInputForPower");
     
    if(!ConnectDB())
    {
        // Erro when connect to database
        if( $_REQUEST['xajax']==null){
            if($arrConfig['debug'] === true)
            {
                echo $objDbSelect->ErrorMsg(), '<br>';
            }
            Die(CONNECT_DB_ERR);
        }else{
            $_POST['xajax']='ajxHelp';
        }

    }
   
    $sIndexFile = TEMPL_PATH.$arrConfig['lang'].'/help.html';
    $objTemplate->LoadTemplate($sIndexFile, 'UTF-8');
     
     $tplXajaxScript = $objXajax->getJavascript('scripts/xajax');
     $objXajax->processRequests(); 
     initPage();
         
    // Include modules file, all process in this module file. 
    if(file_exists($sIncFile))
    {
        include_once($sIncFile);
    } 
    
    function initPage(){
        global $strResult,$strContent,$strScreenLink;
        GetViewForCombo("blkcboView");
        GetViewLinkForCombo("blkcboViewLink"); 
        $strScreenLink=GetScreedLinked();        
        $arrResult = createTree(true);
        $strResult= $arrResult[0];
        $strContent= $arrResult[1];  
    }
     
    function ajxHelp($arrParams=null)
    {
        $objResponse = new xajaxResponse();
        $objResponse->SearchRedirect('help.php');
        return $objResponse->getXML();
    }
      
    //CloseDB();       
    $objTemplate->Show(); 
    
    /*
    *   createTree : tao cay de hien thi noi dung huong dan
    *   $autho ==1 la admin
    *   $autho ==0 la khach hang thuong
    * 
    */
    
    function createTree($autho=false){        
        global $objDbSelect,$dvopen,$spopen,$indexHistory,$hiddenTitle,$firstTitle;
        
        $getfile_id ='';
        $dvopen='0';
        $spopen='0';
        $match_file_id = 0;
        $indexHistory=0;
        $firstTitle= "Tổng quan hướng dẫn sử dụng";
        $hiddenTitle ='<input type=\'hidden\' id=\'hdTitle_0\' value=\'Tổng quan hướng dẫn sử dụng\' />';
        if(isset($_GET['file_id'])){            
             $getfile_id = $_GET['file_id'];
        }
        $father_open ='';
        if($getfile_id!=''){
          $sql_father = "select folder_father_id from tbl_help where id = $getfile_id  and active=1";
          $arrfatheropen = $objDbSelect->GetArray($sql_father);
          if(count($arrfatheropen)>0){
             $father_open = $arrfatheropen[0]['folder_father_id'] ;
             $dvopen = $getfile_id ;
             $spopen = $getfile_id ; 
             $match_file_id=1;
             $indexHistory = $getfile_id;             
          } 
        }
        $strResult = '';
        $strContent = '';
        $where ='';
        $sqlpower     =  'select powers FROM tbl_roles where id = '.$_SESSION['roles'];
        $arrpower     =  $objDbSelect->GetArray($sqlpower);
        $strpower     =  $arrpower[0]['powers'];
        $powerExplode =  explode(';',$strpower);
        $strpowerlast='0';
        for($i=0;$i<count($powerExplode);$i++){
            $arrtemp = explode(':',$powerExplode[$i]) ;
            if($arrtemp[0]!=''){
               $strpowerlast .= ','.$arrtemp[0] ;   
            }           
        }
        $powergroup=$_SESSION['group']; 
        if($powergroup==POWERID_ADMINISTRATOR){
            $autho = true;
        } else{
           $autho=false; 
        }
        if(!$autho){
            $where = "where (active =1 and (screenid in ($strpowerlast) or ((group_id like '$powergroup,%' or group_id like 
            '%,$powergroup,%' or group_id like '%,$powergroup') and  screenid =-1)  or type =1)  ) or folder_father_id=0";              
        }
         $lang='';
         if($_SESSION['lang']=='en'){
           $lang='_en';  
         }
        $sql ="select id,`type`,`order`,folder_father_id,name$lang as name,replace(content_file$lang,'display:non','display:none') as  content_file,active,screenid,group_id 
        from tbl_help $where order by folder_father_id, `type`,`order` ";
        
        $arrHelp =  $objDbSelect->getArray($sql);
        $folder = false;
        $file = false;
        $first_time = true;
        $name_root='';
        $name_root= $arrHelp[0]['name'] ;
        $rootfunc = '';
        $class_root = 'folderrootuser';
        $distance ='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        if($autho){ 
        $distance ='';
        //$rootfunc = 'ondblclick="renamehtml(\'sp0\',\''.$name_root.'\')"';
        $rootfunc='';
        $class_root = 'folderroot';          
         for($i = 1;$i<count($arrHelp);$i++){
          $invisible ='';
          if($arrHelp[$i]['active']==1){
             $invisible = 1; 
          } 
          $classfoder = 'folder'.$invisible;
          $classfile = 'file'.$invisible;
          if($arrHelp[$i]['id']==$getfile_id){
              $classfile.=' selectStatus';
              $firstTitle =  $arrHelp[$i]['name'] ;  
              //$match_file_id = 1;
          }
          $display ='none';
          if($arrHelp[$i]['id']==$getfile_id){
              $display = "''";
          }              
               if($arrHelp[$i]['type']==1){// co nghia la folder;
                   $folder_id = 'fd'.$arrHelp[$i]['id'];
                   $classclosed='closed';
                   if($arrHelp[$i]['id']==$father_open){
                     $classclosed='';  
                   }
                       if($first_time){
                          $strResult .= '<li class="'.$classclosed.'"><span  class="'.$classfoder.'" id="'.$folder_id.'">&nbsp;&nbsp;'.$arrHelp[$i]['name'].'</span><ul>'  ;
                          $first_time=false;                      
                       }else{
                          $strResult .= '</ul></li> <li class="'.$classclosed.'"><span  class="'.$classfoder.'" id="'.$folder_id.'">&nbsp;&nbsp;'.$arrHelp[$i]['name'].'</span><ul>'  ;  
                       }
               }else{//la item dung de hien thi
                       $tempid =   trim($arrHelp[$i]['id']);
                       $tempname = trim($arrHelp[$i]['name']);
                       $hiddenTitle .='<input type=\'hidden\' id=\'hdTitle_'.$tempid.'\' value=\''.$tempname.'\' />'; 
                       $file_id = 'fl'.$arrHelp[$i]['id'];                       
                       $dv = 'dv'.$arrHelp[$i]['id'];
                       $content = $arrHelp[$i]['content_file'];
                       $strResult .= '<li><span id="'.$file_id.'"  class="'.$classfile.'" onclick="displaydv(\''.$dv."','".$file_id.'\');">&nbsp;&nbsp;'.$arrHelp[$i]['name'].'</span></li> '  ;
                       $strContent .=   '<div id="'.$dv.'" style="display:'.$display.'">'.$content.'</div>';  
               }
           }
          $strResult .= '</ul></li>'; 
        }else{
          for($i = 1;$i<count($arrHelp);$i++){
          $classfoder = 'folderuser';
          $classfile = 'fileuser'; 
          $classclosed='closed';
          $display ='none';
          if($arrHelp[$i]['id']==$getfile_id){
              $firstTitle =  $arrHelp[$i]['name'] ; 
              $display = "''";
          }
          if($arrHelp[$i]['id']==$getfile_id){
              $classfile.=' selectStatus';
          }
           if($arrHelp[$i]['id']==$father_open){
             
             $classclosed='';  
           }             
               if($arrHelp[$i]['type']==1){// co nghia la folder;
                 $folder_id = 'fd'.$arrHelp[$i]['id']; 
                       if($first_time){
                          $strResult .= '<li class="'.$classclosed.'"><span  class="'.$classfoder.'" id="'.$folder_id.'">&nbsp;'.$arrHelp[$i]['name'].'</span><ul>'  ;
                          $first_time=false;                      
                       }else{
                          $strResult .= '</ul></li> <li class="'.$classclosed.'"><span  class="'.$classfoder.'" id="'.$folder_id.'">&nbsp;'.$arrHelp[$i]['name'].'</span><ul>'  ;  
                       }
               }else{
                        $tempid =   trim($arrHelp[$i]['id']);
                       $tempname = trim($arrHelp[$i]['name']);
                       $hiddenTitle .='<input type=\'hidden\' id=\'hdTitle_'.$tempid.'\' value=\''.$tempname.'\' />'; 
                       $file_id = 'fl'.$arrHelp[$i]['id'];
                       $dv = 'dv'.$arrHelp[$i]['id'];
                       $content = $arrHelp[$i]['content_file'];
                       $strResult .= '<li><span class="'.$classfile.'" id="'.$file_id.'"  onclick="displaydv(\''.$dv."','".$file_id.'\');">&nbsp;'.$arrHelp[$i]['name'].'</span></li> '  ;
                       $strContent .=   '<div id="'.$dv.'" style="display:'.$display.'">'.$content.'</div>';  
               }
           }
          $strResult .= '</ul></li>';                
        }
        $strResult = '<ul id="example1" class="filetree">  
        <li ><span  '.$rootfunc.'  class="'.$class_root.'" id="sp0" onclick="displaydv(\'dv0\',\'fl0\');">'.$distance.$name_root.'</span>  
        <ul id ="ulroot">'.$strResult.'</ul>';
        if($match_file_id==0){
            $strContent =   '<div id="dv0" >'.$arrHelp[0]['content_file'].'</div>'.$strContent; 
        }else{
            $strContent =   '<div id="dv0" style="display:none">'.$arrHelp[0]['content_file'].'</div>'.$strContent;
        }
        $arrResult[0]= $strResult;
        $arrResult[1]= $strContent; 
       // echo $strResult;die(); 
        return  $arrResult;
        
    }
    
    function deletehelp($params_id,$type){
        global $objDbUpdate;
        $objResponse = new xajaxResponse();
        $sql=''; 
        if($type=='fd'){
          $sql = 'delete from tbl_help where folder_father_id='.$params_id;   
        }else{
          $sql = 'delete from tbl_help where id='.$params_id;  
        }
        if(!$objDbUpdate->Execute($sql)){
           $objResponse->SearchAlert('xoa that bai') ;
        }else{
           $objResponse->SearchRedirect('help.php');
        }
        return $objResponse->getXML();
    }
    
    function updatevisible($params_id,$type){
        global $objDbUpdate;
        $objResponse = new xajaxResponse();
        $sql='';
        $param_new = substr($params_id,2); 
        $sql = "update tbl_help set active = $type where id=$param_new";
        if(!$objDbUpdate->Execute($sql)){
           $objResponse->SearchAlert('Cập nhật thất bại') ;
        }else{
            $objResponse->SearchRedirect('help.php');
        }
        return $objResponse->getXML();
    }
    
    
    function renamehelp($params_id_new,$name,$oldname){
        global $objDbUpdate,$objDbSelect;
        $objResponse = new xajaxResponse(); 
        $col ='id' ;
        $sql='';
        $lang ='';
        $name = trim($name);
        if($_SESSION['lang']=='en'){
          $lang = '_en';  
        }
        $params_id = substr($params_id_new,2);
        if($params_id==0){
          $col = 'folder_father_id';
          //   
        }else{
          $sqltype = " select `type` from tbl_help where $col=$params_id ";
          $arrtype = $objDbSelect->GetArray($sqltype);
          $type = $arrtype[0]['type'] ;
          $name = createName($name,$type,$params_id) ;
        }
        $sql = " update tbl_help set name$lang = '$name' where $col=$params_id ";
       // echo $sql;die();
        if(!$objDbUpdate->Execute($sql)){
           $objResponse->SearchAlert('Thay tên thất bại') ; 
           $name = $oldname;            
        }
        $scriptCall = "SearchScript('$params_id_new','$name')";
        $objResponse->SearchScriptCall($scriptCall);
        return $objResponse->getXML();
    }
    
     function copyhelp($params_id,$father_id,$cut=0){
        global $objDbUpdate,$objDbSelect;
        $objResponse = new xajaxResponse();
        $params_id = substr($params_id,2) ;
        $father_id = substr($father_id,2) ;
        $lang ='';
        if($_SESSION['lang']=='en'){
           $lang='_en'; 
        }
        $sqlmax="select max(`order`) from tbl_help where father_id = $father_id and id<>$father_id";
        $arrordermax = $objDbSelect->GetArray($sqlmax);
        $ordermax = $arrordermax[0]['order']+1;
        
        $selectname ="select name as name,name_en as name_en from tbl_help where id = $params_id";
        $arrname = $objDbSelect->GetArray($selectname); 
        $name =   $arrname[0]['name'];
        $name_en =   $arrname[0]['name_en'];
        $name = createnameforcopy($name,$params_id,$father_id) ;
        $name_en =  createnameforcopy($name_en,$params_id,$father_id,'_en') ;
        $selectinsert='';
        if($cut==1){
             $selectinsert =" update tbl_help set `order`= $ordermax , folder_father_id = $father_id ,name='$name',name_en='$name_en' where id = $params_id";
        }else{
          $selectinsert  = "insert into tbl_help(`type`,`order`,name,name_en,folder_father_id,content_file,content_file_en,created_date,created_user,active,screenid,group_id) 
        select `type`, $ordermax ,'$name','$name_en',$father_id ,content_file,content_file_en,created_date,created_user,active,screenid,group_id from tbl_help where id = $params_id" ;  
        }  
       // echo $selectinsert   ; die();    
        if(!$objDbUpdate->Execute($selectinsert)){
            $objResponse->SearchAlert('Sao chép thất bại.') ;             
        }else{
           $objResponse->SearchRedirect('help.php');
        }
        return $objResponse->getXML();
    }
    
     function Searchnew($name){
        global $objDbUpdate,$objDbSelect;
        $objResponse = new xajaxResponse();
        $name = Searchslashes($name) ;
        $id= -1;
        $name = createName($name,1);      
        $selectinsert  = "insert into tbl_help(`type`,`order`,`name`,created_date,active) 
        values(1, 0 ,'$name',now(),1 )" ;
        if(!$objDbUpdate->Execute($selectinsert)){
           $objResponse->SearchAlert('Thêm mới thất bại.') ;
                     
        }else{
            $selectid = "select id from tbl_help where folder_father_id is null and name = '$name'";
            $arrid =    $objDbSelect->GetArray($selectid);
            if(count($arrid)>0){
              $id = $arrid[0]['id'];  
            } 
            $sqlupdate = "update tbl_help set folder_father_id = id where folder_father_id is null and name = '$name'" ;             
            $objDbUpdate->Execute($sqlupdate);
        }
        $scriptCall = "Searchfoldernew($id,'$name')";
        $objResponse->SearchScriptCall($scriptCall)  ;
        return $objResponse->getXML();
    }
    
    function createnameforcopy($name,$id,$father_id,$lang=''){
          global $objDbSelect; 
        $sql ="select id from tbl_help where name$lang = '$name' and `type`=2 and folder_father_id = $father_id";
             $arrid = $objDbSelect->GetArray($sql);
             $match = true;
             $nameResult = $name;
             $startIndex=2;
             if(count($arrid)>0){
                 while($match){
                     $nametemp = "$name ($startIndex)";
                     $sqlmacth ="select id from tbl_help where name$lang = '$nametemp' and `type`=2 and folder_father_id =  $father_id";
                     $arrid = $objDbSelect->GetArray($sqlmacth);
                    if(count($arrid)>0){
                       $startIndex++; 
                    }else{
                      $nameResult = $nametemp;
                      $match =false;
                      break;  
                    }
                 }
             }
             return   $nameResult;
    }
    
    function createName($name,$type,$id=''){
        global $objDbSelect;
        $startIndex=2;
        $match = true;
        $lang = '';
        if($_SESSION['lang']=='en'){
           $lang='_en'; 
        }
        $nameResult;
        $cond =  ''  ;
        if($id!=''){
          $cond =" and id<> $id"  ;
        }
        if($type==1){ // neu la folder
             $sql ="select id from tbl_help where name$lang = '$name' and `type`=1 $cond ";
             $arrid = $objDbSelect->GetArray($sql);
             if(count($arrid)>0){
                 while($match){
                     $nametemp = "$name ($startIndex)";
                     $sqlmacth ="select id from tbl_help where name$lang = '$nametemp' and `type`=1 $cond"; 
                     $arrid = $objDbSelect->GetArray($sqlmacth);
                    if(count($arrid)>0){
                       $startIndex++; 
                    }else{
                      $nameResult = $nametemp;
                      $match =false;
                      break;  
                    }
                 }
             }else{
                 $nameResult = $name;
             }  
        }else{
             $sql ="select id from tbl_help where name$lang = '$name' and `type`=2 and folder_father_id = 
             (select folder_father_id from tbl_help where id = $id) $cond";
             $arrid = $objDbSelect->GetArray($sql);
             if(count($arrid)>0){
                 while($match){
                     $nametemp = "$name ($startIndex)";
                     $sqlmacth ="select id from tbl_help where name$lang = '$nametemp' and `type`=2 and folder_father_id =
             (select folder_father_id from tbl_help where id = $id) $cond";                      
                     $arrid = $objDbSelect->GetArray($sqlmacth);
                    if(count($arrid)>0){
                       $startIndex++; 
                    }else{
                      $nameResult = $nametemp;
                      $match =false;
                      break;  
                    }
                 }
             }else{
                 $nameResult = $name;
             }  
            
        } 
        return $nameResult;        
    }
//******************Phuog Search***************************************************************************************
   
                                                                        
// Ham xu ly lay thong tin tu co so su lieu dien vao form
function ajxFillData($sID)
{       global $objDbSelect;

        $objResponse = new xajaxResponse();  
        $tblName ='tbl_help' ;
        $lang = $_SESSION['lang'];                
        $sql ="select sub.*,fa.name as fathername from tbl_help sub inner join tbl_help fa on sub.folder_father_id = fa.id where sub.id = $sID" ;
       // echo $sql;die();
        $arrItem =  $objDbSelect->GetArray($sql);                             
        if(!$arrItem){
            $objResponse->SearchAlert(SYSTEM_ERR_GETDATA);
            return $objResponse->getXML();
        }
        
      
         $flgmacth=false;
        $strcombobox = GetViewForComboForEdit($sID,$flgmacth);
       // echo  $strcombobox;die();
        $subname  = $arrItem[0]['fathername'];
        $position =  $arrItem[0]['order'];
        $active   = $arrItem[0]['active'];
                
        $namevi   = $arrItem[0]['name'];
        $nameen   =  $arrItem[0]['name_en'];
        $contentvi = $arrItem[0]['content_file'];
        $contenten = $arrItem[0]['content_file_en'];
        $screenid  = $arrItem[0]['screenid'];
        $group_id  = $arrItem[0]['group_id'];
               
        $objResponse->SearchAssign('hdeditscreenid','value',$screenid);
        $objResponse->SearchAssign('labelSubVi','innerHTML',$subname);
        $objResponse->SearchAssign('tdcboView','innerHTML','');    
        $objResponse->SearchAssign('tdcboView','innerHTML',$strcombobox);
        
        if($flgmacth){
         $objResponse->SearchAssign('screenLinked','innerHTML','Liên kết đến trang hướng dẫn :'.$namevi);        
        } 
        
       
        $objResponse->SearchAssign('txtPosition','value',$position); 
        if($active == 1){
              $objResponse->SearchScript("$('#chkActive').attr('checked',true);");
        }else{
             $objResponse->SearchScript("$('#chkActive').attr('checked',false);");
        }
               
        $objResponse->SearchAssign('txtNameVi','value',$namevi);        
        $objResponse->SearchAssign('txtNameEn','value',$nameen);
        $objResponse->SearchAssign('hdoldorder','value',$position); 
        
        $objResponse->SearchAssign('hdContentVi','value',$contentvi);
        $objResponse->SearchScript(" var content_vi = $('#hdContentVi').val();
                                    CKEDITOR.instances['txtContentVi'].setData(content_vi);"
                                    ); 
        $objResponse->SearchAssign('hdContentEn','value',$contenten);       
        $objResponse->SearchScript(" var content_en = $('#hdContentEn').val();
                                    CKEDITOR.instances['txtContentEn'].setData(content_en);"
                                    );
       if($screenid!='-1'){
          $objResponse->SearchScript("$('#trPower').css('display', 'none');");  
       }else{
         $objResponse->SearchScript("$('#trPower').css('display', '');"); 
         $objResponse->SearchScriptCall("fillcheckbox('$group_id')");   
       }

        return $objResponse->getXML();
}
 function GetHelpNameFromID($sID)
 {
        global  $objDbSelect, $lang;
        $refix ="";
        if($lang == "en")
        {
            $refix = "_en";
        }else{
            $refix="";
        }
        $sSQL = "SELECT name$refix as name FROM tbl_help WHERE id = ".$sID;
        $rs   = $objDbSelect->Execute($sSQL);
        return $rs->fields['name'] ;
 }

/*
* dung de review tinh nang moi voi id = id truyen vao
* 
* 
*/


////////////////////////////////////////////////////////////////////////////////////////////
  
function ajxSaveEdit($arg)
  {        
        global  $objDbUpdate,$objDbSelect;   
        $objResponse = new xajaxResponse();   
           
        $filename = "";
        $status   = "";
        $tblName ='tbl_help' ;
        $createddate = date('Y-m-d H:i:s');
        $cusr = $_SESSION['username'];
        $arrPower = $arg['str_group']  ;
        if($arg['view']!=-1){
          $arrPower=1;  
        } 
        $fatherid = substr($arg['fatherid'],2); 
        $type = substr($arg['fatherid'],0,2);
     if($type=='fd')
     {   
            $sql ="";           
                $sql.= "insert into ".$tblName." (`type`,`order`,folder_father_id,name,content_file,created_date,created_user,active,screenid,name_en,content_file_en,group_id) 
                values(
                2,
                '".$arg['position']."',
                 '".$fatherid."',
                 '".mysql_real_escape_string($arg['namevi'])."',
                 '".mysql_real_escape_string($arg['contentvi'])."',
                 '$createddate',
                 '$cusr',
                  ".$arg['active'].",
                  '".$arg['view']."', 
                  '".mysql_real_escape_string($arg['nameen'])."',
                  '".mysql_real_escape_string($arg['contenten'])."',
                  '$arrPower'
                                   
                );";
                if($arg['position']!=$arg['maxorder']){
                 $sqlupdate = 'update tbl_help set `order` = `order` +1  where `type`=2 and `order` >=' .$arg['position'].' and folder_father_id ='.$fatherid;   
                 $objDbUpdate->Execute($sqlupdate);
                }
            $res = $objDbUpdate->Execute($sql);            
            if(!$res) {
                $objResponse->SearchAlert('Lưu thất bại') ;      
            }
           // echo $sql; die();                           
         
        
     }
     else if ($type=='fl')
     {  
         if($arg['position']!=$arg['oldorder']){
             $sqlfather_id = "select folder_father_id from tbl_help where id = $fatherid";
             $arrFId = $objDbSelect->GetArray($sqlfather_id);
             $Fid = $arrFId[0]['folder_father_id'];
                 if($arg['position']>$arg['oldorder']){
                     $sqlupdate = 'update tbl_help set `order` = `order` -1  where `type`=2 and `order` >=' .$arg['oldorder'].
                     ' and `order` <=' .$arg['position'].' and folder_father_id ='.$Fid;   
                     $objDbUpdate->Execute($sqlupdate); 
                    }else{
                         $sqlupdate = 'update tbl_help set `order` = `order` + 1  where `type`=2 and `order` <=' .$arg['oldorder'].
                         ' and `order` >=' .$arg['position'].' and folder_father_id ='.$Fid;      
                         $objDbUpdate->Execute($sqlupdate);
                    } 
           
         }

                   
        $sSQL="";
        $sSQL.= "UPDATE $tblName SET  `order` = '".$arg['position']."',
                                    name = '".mysql_real_escape_string($arg['namevi'])."',
                                    content_file ='".mysql_real_escape_string($arg['contentvi'])."',
                                    active    = ".$arg['active']." ,
                                    screenid = ".$arg['view']." , 
                                    name_en = '".mysql_real_escape_string($arg['nameen'])."', 
                                    content_file_en  ='".mysql_real_escape_string($arg['contenten'])."',
                                    group_id  ='".$arrPower."' 
                WHERE  id = ".$fatherid;
                               // echo   $sSQL;die();

        $resUpdate = $objDbUpdate->Execute($sSQL);        
        if(!$resUpdate) {            
           $objResponse->SearchAlert('Lưu thất bại') ;      
        } 
     }
    $objResponse->SearchRedirect('help.php');
     return $objResponse->getXML();        
  }
       
    function GetViewForCombo($blk_view)
    {
    global $objTemplate, $objDbSelect,$lang;      
    //$sSQL = "SELECT id, name$lang as name FROM tbl_menu WHERE id NOT IN (SELECT screenid FROM tbl_help WHERE screenid IS NOT NULL) ORDER BY name$lang";
    $sSQL = "SELECT id, name$lang as name FROM tbl_menu  ORDER BY name$lang"; 
    $objTemplate->MergeBlock($blk_view, $objDbSelect->_connectionID, $sSQL);
    }
    
    function GetViewLinkForCombo($blk_view)
    {
    global $objTemplate, $objDbSelect,$lang;     
    $tbl_postfix = '';
    if($lang=='en'){
     $tbl_postfix='_en';   
    } 
    $sSQL = "SELECT id, name$tbl_postfix as name FROM tbl_help where `type`=2 ORDER BY name$tbl_postfix";
    $objTemplate->MergeBlock($blk_view, $objDbSelect->_connectionID, $sSQL);
    }
    
    function GetViewForComboForEdit($id,&$flg)
    {
        global $objTemplate, $objDbSelect,$lang;      
       // $sSQL = "SELECT id, name$lang as name FROM tbl_menu WHERE id NOT IN (SELECT screenid FROM tbl_help WHERE screenid IS NOT NULL and id<>$id)  ORDER BY name$lang";
        $sSQL = "SELECT id, name$lang as name FROM tbl_menu ORDER BY name$lang";                                                        
       // echo $sSQL;die();
        $sqlScreenid = "SELECT screenid FROM tbl_help WHERE screenid IS NOT NULL and id=$id";
        $arrscreenid = $objDbSelect-> GetArray($sqlScreenid);
        $screenid = -1;
        $flg=false;
        if(count($arrscreenid)>0){
         $screenid = $arrscreenid[0]['screenid'];    
        }        
        $arrCombo = $objDbSelect-> GetArray($sSQL);
        $tr_combo =    "";
        for($i=0;$i<count($arrCombo);$i++)
        {
           $idoption = $arrCombo[$i]['id'];
           $nameoption = $arrCombo[$i]['name'];
           if($arrCombo[$i]['id']==$screenid)
           { $flg = true;
             $tr_combo .="<option value='$idoption' selected='selected'>$nameoption</option> "; 
           }
           else
           {
             $tr_combo .="<option value='$idoption'>$nameoption</option> "; 
           } 
        }
        //echo $tr_combo;die();
        return   '<select id="cboView" name="cboView" style="width:340px;" onchange="SetPower(this.value);" ><option value="-1">-- No --</option>'.$tr_combo.'</select>';
         
    }    
    
    function GetInputForPower(){
        global $objTemplate,$objDbSelect , $lang;
        $objResponse = new xajaxResponse(); 
        $sSQLPower ="SELECT id, name$lang as name FROM tbl_powergroup WHERE id <> 1 and id<>".POWERID_SUBCUSTOMER;
        $r = $objDbSelect->GetArray($sSQLPower);
        $strreturn ='<table ><tr>';
        //$strreturn.='<td rowspan="3"><input type="checkbox" name="chkAll" id="chkAll" value="all" onclick="fn_CheckAll();"/><b>Chọn tất cả</b></td>'; 
        for($i=0; $i < count($r);$i++)
        {
            $strreturn.='<td>&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="chkPower" onclick="fn_checkedchange();" value="'.$r[$i]["id"].'"/></td>';
            $strreturn.='<td><b>'.$r[$i]["name"].'</b></td>';
            if($i==2)
            {
                $strreturn.='</tr><tr>';
            }
        }
        $strreturn.='</tr></table>';                     
        $objResponse->SearchAssign('tdPower', 'innerHTML', $strreturn);                
        return $objResponse->getXML();  
    } 
    function fillIntroduce() {
        global  $objDbSelect ;
        
        $objResponse = new xajaxResponse(); 
        $sql ='select content_file, content_file_en from tbl_help where folder_father_id=0';
        $arrcontent =  $objDbSelect->GetArray($sql);
        $contentVi = $arrcontent[0]['content_file'] ;
        $contentEn = $arrcontent[0]['content_file_en'] ;       
        $objResponse->SearchAssign('hdContentVi_Introduce','value',$contentVi);
        $objResponse->SearchScript(" var content_vi_Introduce = $('#hdContentVi_Introduce').val();
                                    CKEDITOR.instances['txtContentVi_Introduce'].setData(content_vi_Introduce);"
                                    ); 
        $objResponse->SearchAssign('hdContentEn_Introduce','value',$contentEn);       
        $objResponse->SearchScript(" var content_en_Introduce = $('#hdContentEn_Introduce').val();
                                    CKEDITOR.instances['txtContentEn_Introduce'].setData(content_en_Introduce);"
                                    );
                                    
        return $objResponse->getXML(); 
    }
    
    function saveIntroduce($arrparam){
      global  $objDbUpdate ;
      $objResponse = new xajaxResponse();   
       $contentVi = Searchslashes($arrparam['contentVi']);
       $contentEn = Searchslashes($arrparam['contentEn']);
       $sqlupdate = "update tbl_help set content_file = '$contentVi',content_file_en = '$contentEn' where folder_father_id=0"  ;
     // echo  $sqlupdate; die();
       $objDbUpdate = $objDbUpdate->Execute($sqlupdate);
       $objResponse->SearchRedirect('help.php');
       return $objResponse->getXML();        
    }
    function fillArange($id){
       global  $objDbSelect ;
       $objResponse = new xajaxResponse(); 
       $lang='';
       if($_SESSION['lang']=='en'){
          $lang='_en';  
       }
       $id =substr($id,2);
       $sql = "select id,`type`,`order`,name$lang as name,active
        from tbl_help where folder_father_id='$id' order by `type`,`order` ";
        $arrfile =  $objDbSelect->GetArray($sql);
        $strlist='';        
        for($i=1;$i<count($arrfile);$i++){
            $nametemp = trim($arrfile[$i]['name']);
            $strlist .= "<li><span id='order_$i' onclick='changestatus($i);' class='file1'>$nametemp</span></li>" ;
        }
        $namefolder =  trim($arrfile[0]['name']);
        $strlist = "<ul id='listmenu' class='filetree'><li><span id='folder' class='folder1'>$namefolder</span><ul>$strlist</ul></li></ul>" ;        
        $objResponse->SearchAssign('tdlistfile','innerHTML',$strlist);
        $objResponse->SearchAssign('noOfItem','value',count($arrfile)-1);         
        return $objResponse->getXML(); 
    }
    
    function saveArange($arrParams,$fatherid){
      global  $objDbUpdate ;
      $fatherid=substr($fatherid,2) ;
      $objResponse = new xajaxResponse();
       $lang='';
       if($_SESSION['lang']=='en'){
          $lang='_en';  
       }
      foreach($arrParams as $key=>$value){
          $value = Searchslashes($value) ;
         $sqlUpdate = "update tbl_help set `order` = $key where folder_father_id = $fatherid and `type`= 2 and name$lang='$value'" ;
         $objDbUpdate->Execute($sqlUpdate);
      }
      $objResponse->SearchRedirect('help.php');   
      return $objResponse->getXML();  
    } 
    function getLastOrder($father_id){
        global $objDbSelect;
        $sql= "select (max(`order`) +1) as orderfile from tbl_help where folder_father_id = $father_id and `type`=2 ";
        $arrorder = $objDbSelect->GetArray($sql);
        $result =1;
        if(count($arrorder)>0){
          $result =  $arrorder[0]['orderfile']; 
        }
        return $result;
    }
   function  fillorder($fatherid){
      global  $objDbUpdate ;
      $objResponse = new xajaxResponse();
      $fatherid=substr($fatherid,2) ;
      $lastorder = getLastOrder($fatherid);
      $objResponse->SearchAssign('txtPosition','value',$lastorder);
      $objResponse->SearchAssign('hdmaxorder','value',$lastorder);      
      return $objResponse->getXML(); 
      
   }
   function GetScreedLinked(){
       global  $objDbSelect,$lang ;
        $temp = '';
        if($lang=='en'){
           $temp='_en'; 
        }
        $sSQLPower ="SELECT screenid, name$temp as name FROM tbl_help where screenid is not null and screenid<>-1";
        $r = $objDbSelect->GetArray($sSQLPower);
        //echo $sSQLPower;die();
        $str = '';
        for($i=0;$i<count($r);$i++){
            $screened= $r[$i]['screenid'];
            $name= $r[$i]['name'];
           $str.="<input type='hidden' name='scrLinked_$screened' id='scrLinked_$screened' value='$name'/> " ;
        }
        return $str;
   } 

//End Phuong Search